package service

import (
	"fmt"
	"gligli/cache"
	"gligli/model"
	"gligli/serializer"
	"math/rand"
	"strconv"
	"strings"

	//"submail_go_sdk/submail/sms"
	//"gitee.com/lcl1024/submail_go_sdk/submail/sms"
	//"github.com/dev-submail/submail_go_sdk/submail/sms"
	"gligli/submail/sms"
	"time"
)

type MsgCodeService struct {
	UserName string `form:"tel"  json:"tel" binding:"required"`
	UUID string `form:"uuid" json:"uuid" binding:"required"`
}

// 生成验证码并发送到指定手机
func (service *MsgCodeService) Send(tel MsgCodeService) *serializer.Response {

	// 验证手机号是否已经注册
	user := model.User{}
	err := model.DB.Where("user_name= ?", tel.UserName).First(&user).Error
	if err == nil {
		fmt.Println("该手机号已经被注册", tel)
		return &serializer.Response{
			Status: 40002,
			Msg:    "该手机号已经被注册",
		}
	}
	// 生成随机数
	t := rand.New(rand.NewSource(time.Now().UnixNano()))
	//四位 1000-9999
	size := t.Intn(8999) + 1000
	fmt.Println("随机数：", size)
	// 短信的配置信息
	config := make(map[string]string)
	//预先创建好的appid
	config ["appid"] = "39536"
	//预先获得的app的key
	config ["appkey"] = "8f007b31cd4cccebbd9a5d8ecd561f44"
	//SMS 数字签名模式 normal or md5 or sha1 ,normal = 明文appkey鉴权 ，md5 和 sha1 为数字签名鉴权模式
	config ["signtype"] = "md5"

	//创建 短信 Send 接口
	submail := sms.CreateXsend(config)
	//设置联系人 手机号码+UUID
	submail.SetTo(tel.UserName + tel.UUID)
	fmt.Println("********")
	fmt.Println(tel.UserName + "," +  tel.UUID)
	//设置短信模板id
	submail.SetProject("9rClz")
	//添加模板中的设置的动态变量。如模板为：【xxx】您的验证码是:@var(code),请在@var(time)分钟内输入。
	submail.AddVar("code", strconv.Itoa(size))
	submail.AddVar("time", "5")
	//执行 Xsend 方法发送短信
	xsend := submail.Xsend()
	fmt.Println("短信XSend 接口:", xsend)

	// 验证码是否发送成功
	bo := strings.Contains(xsend, "success")
	if bo != true {
		fmt.Println("短信验证码发送失败 ！")
		return &serializer.Response{
			Status: 40002,
			Msg:    "短信验证码发送失败",
		}
	}

	// 将随机数和手机号存入redis
	state := cache.RedisClient.Set(tel.UserName + tel.UUID, strconv.Itoa(size), time.Second*300)
	if state == nil {
		fmt.Println("验证码存储失败 ！", err)
		return &serializer.Response{
			Status: 40002,
			Msg:    "验证码存储失败",
		}
	}

	return &serializer.Response{
		Status: 0,
		Msg:    "验证码发送成功",
	}
}
